package cn.itcast.service.impl;

import cn.itcast.pojo.Weather;
import cn.itcast.service.WeatherService;
import cn.itcast.utils.CityCodeUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class WeatherServiceImpl implements WeatherService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * @param cityName 城市名称
     * @return 5天的城市天气信息
     */
    @Override
    public List<Weather> getCityWeatherInfo(String cityName) {
        String cityCode = CityCodeUtils.getCityCode(cityName);

        String resp = restTemplate.getForObject("http://t.weather.itboy.net/api/weather/city/" + cityCode, String.class);
        JSONObject object = JSON.parseObject(resp);
        int status = (int) object.get("status");
        if (status == 200) {
            JSONObject data = (JSONObject) object.get("data");
            JSONArray array = (JSONArray) data.get("forecast");
            List<Weather> list = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                JSONObject json = (JSONObject) array.get(i);
                Weather weather = new Weather();
                weather.setType(json.getString("type"));
                weather.setHigh(json.getString("high"));
                weather.setLow(json.getString("low"));
                weather.setYmd(json.getString("ymd"));
                weather.setWeek(json.getString("week"));
                weather.setFx(json.getString("fx"));
                weather.setFl(json.getString("fl"));
                weather.setNotice(json.getString("notice"));
                list.add(weather);
            }
            return list;
        }
        return null;
    }

}
